package com.senseauto.ah8mediacodec.utils;

import android.util.SparseArray;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 之前1920*1088的尺寸大小复用byte[]也是这样的写法，但是oom报错了，现在1920*1080和1920*1280用这个写法
 * 1920*1088的尺寸大小复用byte[]固定用ByteBufferPool的操作
 */
public class ByteBuffer1080Pool {

    //原先的写法，1920*1088的大小的复用这个会oom,所以这个保留了（针对1920*1280和1920*1080的byte[]用这个 ）1920*1088的大小用ByteBufferPool里的
    private static final  SparseArray<List<ByteBuffer>> sparseArray = new SparseArray<>();
    public static ByteBuffer1080Pool instance;
    static {
        synchronized (ByteBuffer1080Pool.class) {
            instance = new ByteBuffer1080Pool( );
        }
    }

    public static ByteBuffer1080Pool getInstance() {
        return instance;
    }

    private ByteBuffer1080Pool( ) {

    }

    //获取指定大小的byte[]
    public ByteBuffer getBuffer(int len) {
        List<ByteBuffer> bufferList = sparseArray.get(len);
        if (bufferList == null) {
            bufferList = new ArrayList<>();
            sparseArray.put(len, bufferList);
        }
        return bufferList.isEmpty() ? ByteBuffer.allocate(len) : bufferList.remove(0);
    }

    public void returnBuffer(byte[] buf) {
        if (buf == null) {
            return;
        }
        List<ByteBuffer> bufferList = sparseArray.get(buf.length);
        if (bufferList == null) {
            bufferList = new ArrayList<>();
            Arrays.fill(buf, (byte)0);
            bufferList.add(ByteBuffer.wrap(buf));
            sparseArray.put(buf.length, bufferList);
        }else{
            Arrays.fill(buf, (byte)0);
            bufferList.add(ByteBuffer.wrap(buf));
        }
    }
}
